export default class compressor {
  static compress(src, callBack) {
    // 创建Image对象
    const MAX_SIZE = 400;
    const QUALITY = 0.8;
    let image = new Image();

    image.onload = function () {
      console.log(image.width, image.height);
      // 通过固定的宽高比压缩
      // 宽大于高的情况
      if (image.width > MAX_SIZE && image.width >= image.height) {
        image.height *= MAX_SIZE / image.width;
        image.width = MAX_SIZE;
      }
      // 宽小于高的情况
      if (image.height > MAX_SIZE && image.height > image.width) {
        image.width *= MAX_SIZE / image.height;
        image.height = MAX_SIZE;
      }
      let canvas = document.createElement('canvas');
      // 获取2d画布
      let ctx = canvas.getContext('2d');
      canvas.width = image.width;
      canvas.height = image.height;
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制图片
      ctx.drawImage(image, 0, 0, image.width, image.height);
      // 生成base64码
      let blob = canvas.toDataURL('image/png', QUALITY);
      // console.log('bbb', blob);
      if (callBack !== undefined) {
        callBack(blob);
      }
      // return blob;
    };

    image.src = src;
  }
}
